# === load relevant libraries
library(data.table)
library(ggplot2)
library(DescTools)
library(plm)
library(lfe)
library(dplyr)
library(sandwich)

rm(list = ls())

# sort stocks based on predicted rating changes in dec 2001
data = readRDS('input_data/monthly_stock_data_for_figure_A8.RDS')
tmp = readRDS('input_data/monthly_stock_predicted_rating_change_for_figure_A8.RDS')
data = merge(data, tmp, by = 'permno'); rm(tmp)

# sort stocks into quintiles by predicted rating changes
tmp = unique(data[, list(drating_pred, permno)])
tmp[, rank := ntile(drating_pred, 5)]
data = merge(data[, rank := NULL], tmp[, list(permno, rank)], by = 'permno'); rm(tmp)

# demean by period, and summarize
data = merge(data, data[, list(m = weighted.mean(value, me_1)), list(yyyymm, var)], by = c('yyyymm','var'))
data[, value := value - m]
data[, m := NULL]
data = data[, list(value = weighted.mean(value, me_1)), list(yyyymm, rank, var)]

# enrich for plotting purposes
data[, date := as.Date(as.character(100*yyyymm+1), '%Y%m%d')]
data = data[rank %in% c(1,2,4,5)]
data[, lab := ifelse(rank == 5, 'Most negatively affected',ifelse(rank == 4, 'Second neg',ifelse(rank == 1, 'Most positively affected', 'Second pos')))]
data_bk = copy(data)
event_date = as.Date('2002-06-01')

# output: Figure A8 (a): ratings
data = copy(data_bk[var == 'rating'])
ggplot(data, aes(x = date, y = value, color = reorder(lab, -rank))) + geom_line(lwd = 1) + theme_classic() + 
  labs(x = NULL, y = 'Demeand rating') + theme(legend.position = c(.75, .8), legend.title = element_blank()) + 
  geom_vline(xintercept = event_date, lty = 3) + coord_cartesian(ylim = c(-.4, 1)) + geom_hline(yintercept = 0, lty = 3, lwd = .2)

# output: Figure A8 (b), cumulative returns
data = copy(data_bk[var == 'ret'])
for (this in unique(data[, rank])){data[rank == this, value := cumsum(log(1+value))]}
rm(this)
ggplot(data, aes(x = date, y = value, color = reorder(lab, -rank))) + geom_line(lwd = 1) + theme_classic() + 
  labs(x = NULL, y = 'Cumulative log return') + theme(legend.position = c(.25, .9), legend.title = element_blank()) + 
  geom_vline(xintercept = event_date, lty = 3) + coord_cartesian(ylim = c(-.15, .3)) + 
  scale_y_continuous(labels = scales::percent_format(accuracy = 1)) + geom_hline(yintercept = 0, lty = 3, lwd = .2)

